package cn.sisyphe.framework.web.exception;

import cn.sisyphe.framework.web.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by heyong on 2017/11/21 16:30
 * Description: 全局错误配置
 *
 * @author heyong
 */
@ControllerAdvice
@ConfigurationProperties(prefix = "sisyphe.exception")
public class GlobalExceptionHandler {

    private final static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 通过配置获取错误
     */
    private Map<String, String> frontendMessage = new HashMap<String, String>();

    /**
     * 捕获dataException错误，替换错误说明
     *
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = DataException.class)
    @ResponseBody
    public ResponseResult jsonExceptionHandler(HttpServletRequest req, Exception e) throws Exception {

        DataException dataException = (DataException) e;
        String errorCode = dataException.getErrorCode();
        String frontendMessage = this.frontendMessage.get(errorCode);

        dataException.setErrorMessage(StringUtils.isEmpty(frontendMessage) ? dataException.getErrorMessage() : frontendMessage);

        ResponseResult responseResult = new ResponseResult();
        responseResult.putException(dataException);

        log.error("error:", e);

        return responseResult;
    }


    public Map<String, String> getFrontendMessage() {
        return frontendMessage;
    }

    public void setFrontendMessage(Map<String, String> frontendMessage) {
        this.frontendMessage = frontendMessage;
    }

}
